﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class ConsigneeAddressController : BaseApiController
    {
        /// <summary>
        /// 获取收货地址列表，默认收货地址放在顶部，其他按照Id正序排列
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IEnumerable<ConsigneeAddress> GetAddressByUserId(int id)
        {
            var list = from c in db.ConsigneeAddress where c.UserId == id && c.IsDelete!=1 orderby c.IsDefault descending,c.Id ascending select c;
            
            return list;
        }

        /// <summary>
        /// 根据id删除（逻辑删除）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public bool Delete() {
            bool result = false;
            string addressId = HttpContext.Current.Request.Form["addressId"];            
            int id = Convert.ToInt32(addressId);
            var address = db.ConsigneeAddress.FirstOrDefault((p) => p.Id == id);
            if (address != null)
            {
                address.IsDelete = 1;
                int r = db.SaveChanges();
                if (r > 0)
                {
                    result = true;
                }
            }
            return result;
        }

        /// <summary>
        /// 设置默认地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public bool DeFaultAddress() {
            bool result = false;
            int userId = Convert.ToInt32(HttpContext.Current.Request.Form["userId"]);
            string addressId = HttpContext.Current.Request.Form["addressId"];
            int id = Convert.ToInt32(addressId);
            if (id > 0)
            {
                var list = from c in db.ConsigneeAddress where c.UserId== userId && c.IsDelete != 1 select c;
                foreach (var item in list)
                {
                    if (item.IsDefault == 1)
                    {
                        item.IsDefault = 0;
                    }
                    if (item.Id == id) {
                        item.IsDefault = 1;
                    }                    
                }
                int r = db.SaveChanges();
                if (r > 0)
                {
                    result = true;
                }
            }
            return result;
        }
    }
}
